<?php
/**
 * Created by PhpStorm.
 * User: JYuans
 * Date: 2019/12/12
 * Time: 11:39
 */
namespace Bstage\Controller;

class TeamExamineResultController extends BstageController {

    /**
     * 获取班子考评权重列表
     */
    public function getTeamWeightList(){
        $team_examine_id = $_REQUEST['team_examine_id']?$_REQUEST['team_examine_id']:$this->errorReturn("缺少班子考评ID");

        $team_list = M("Team")
            ->alias("t")
            ->join("left join __TEAM_EXAMINE_RESULT__ ter on t.team_id = ter.team_id and ter.team_examine_id = ".$team_examine_id)
            ->field("t.team_id,t.name,t.name_abb,ter.down_weight,ter.same_weight,ter.up_weight")
            ->select();

        if(!$team_list){
            $this->returnJson(503,"无数据");
        }

        foreach($team_list as $key=>$value){
            $team_list[$key]['down_weight'] = !empty($value['down_weight'])?floatval(bcmul($value['down_weight'],100)):0;
            $team_list[$key]['same_weight'] = !empty($value['same_weight'])?floatval(bcmul($value['same_weight'],100)):0;
            $team_list[$key]['up_weight'] = !empty($value['up_weight'])?floatval(bcmul($value['up_weight'],100)):0;
        }

        $this->successReturn("获取成功",['list_data'=>$team_list]);
    }

    /**
     * 设置考评权重接口
     */
    public function setWeightAction(){
        $team_examine_id = $_REQUEST['team_examine_id']?$_REQUEST['team_examine_id']:$this->errorReturn("缺少班子考评ID");

        $weight_json = $_REQUEST['weight_json']?$_REQUEST['weight_json']:$this->errorReturn("缺少权重JSON数据");

        $weight_array = json_decode($weight_json,true);
        if(!is_array($weight_array)){
            $this->errorReturn("权重JSON格式错误");
        }
        if(!$weight_array){
            $this->errorReturn("请上传权重数据");
        }

        $team_id_array = array_column($weight_array,0);
        $team_id_array = array_keys(array_flip($team_id_array));
        $check_team_id = M("Team")
            ->where(['team_id'=>['in',$team_id_array]])
            ->count();
        if($check_team_id != count($team_id_array)){
            $this->errorReturn("存在错误班子ID，请重新尝试");
        }

        $model = M();
        $model->startTrans();

        foreach($weight_array as $key=>$value){
            //team_examine_id,team_id,team_name,team_name_abb,down_weight,same_weight,up_weight
            $team_data = M("Team")
                ->where(['team_id'=>$value[0]])
                ->field("name,name_abb")
                ->find();

            $amount_weight = bcadd(bcadd($value[1],$value[2],2),$value[3],2);
            if($amount_weight != 100){
                $model->rollback();
                $this->errorReturn("班子：".$team_data['name']."，权重和必须等于100");
            }

            $check_weight_data = M("TeamExamineResult")
                ->where(['team_examine_id'=>$team_examine_id,'team_id'=>$value[0]])
                ->count();
            if($check_weight_data){
                $new_data = array();
                $new_data['team_name'] = $team_data['name'];
                $new_data['team_name_abb'] = $team_data['name_abb'];
                $new_data['down_weight'] = bcdiv($value[1],100,2);
                $new_data['same_weight'] = bcdiv($value[2],100,2);
                $new_data['up_weight'] = bcdiv($value[3],100,2);
                $new_data['update_time'] = time();

                $update_result = M("TeamExamineResult")
                    ->where(['team_examine_id'=>$team_examine_id,'team_id'=>$value[0]])
                    ->save($new_data);
                if(!$update_result){
                    $model->rollback();
                    $this->errorReturn("修改权重数据失败，请重新尝试");
                }
            }else{
                $new_data = array();
                $new_data['team_examine_id'] = $team_examine_id;
                $new_data['team_id'] = $value[0];
                $new_data['team_name'] = $team_data['name'];
                $new_data['team_name_abb'] = $team_data['name_abb'];
                $new_data['down_weight'] = bcdiv($value[1],100,2);
                $new_data['same_weight'] = bcdiv($value[2],100,2);
                $new_data['up_weight'] = bcdiv($value[3],100,2);

                $add_result = M("TeamExamineResult")
                    ->add($new_data);
                if(!$add_result){
                    $model->rollback();
                    $this->errorReturn("添加权重数据失败，请重新尝试");
                }
            }
        }

        $model->commit();
        $this->successReturn("提交成功");
    }

    /**
     * 获取班子考评_综合考评最终结果接口
     */
    public function getTeamExamineResultList(){
        $team_examine_id = $_REQUEST['new_team_examine_id']?$_REQUEST['new_team_examine_id']:$this->errorReturn("缺少班子考评ID");

        $team_data = M("TeamExamine")
            ->where(['team_examine_id'=>$team_examine_id])
            ->field("status,item_json")
            ->find();
        if(!$team_data){
            $this->errorReturn("班子考评ID错误，请重新尝试");
        }
        if($team_data['status'] < 2){
            $this->errorReturn("考核未开始，无法获取最终结果详情");
        }

        $team_examine_result = M("TeamExamineResult")
            ->where(['team_examine_id'=>$team_examine_id])
            ->getField("team_id,team_name,team_name_abb,down_weight,same_weight,up_weight");

        if(!$team_examine_result){
            $this->returnJson(503,"无数据");
        }

        foreach($team_examine_result as $key=>$value){
            $team_examine_result[$key]['team_id'] = $key;
            $team_examine_result[$key]['down_examine_user_count'] = 0;
            $team_examine_result[$key]['down_item_result'] = array();
            $team_examine_result[$key]['down_score'] = 0;
            $team_examine_result[$key]['same_examine_user_count'] = 0;
            $team_examine_result[$key]['same_item_result'] = array();
            $team_examine_result[$key]['same_score'] = 0;
            $team_examine_result[$key]['up_examine_user_count'] = 0;
            $team_examine_result[$key]['up_item_result'] = array();
            $team_examine_result[$key]['up_score'] = 0;
            $team_examine_result[$key]['avg_item_result'] = array();
            $team_examine_result[$key]['avg_score'] = 0;
        }

        $down_result_list = M("TeamExamineRelationDown")
            ->where(['team_examine_id'=>$team_examine_id,'comprehensive_status'=>1])
            ->field("be_examine_team_id,item_result,item_score")
            ->select();
        foreach($down_result_list as $key=>$value){
            $item_result = json_decode($value['item_result'],true);
            if(!$team_examine_result[$value['be_examine_team_id']]['down_item_result']){
                $team_examine_result[$value['be_examine_team_id']]['down_item_result'] = $item_result;
            }else{
                for($i=0;$i<count($item_result);$i++){
                    $team_examine_result[$value['be_examine_team_id']]['down_item_result'][$i] = bcadd(
                        $team_examine_result[$value['be_examine_team_id']]['down_item_result'][$i],
                        $item_result[$i],2);
                }
            }
            $team_examine_result[$value['be_examine_team_id']]['down_examine_user_count']++;
            $team_examine_result[$value['be_examine_team_id']]['down_score'] = bcadd(
                $team_examine_result[$value['be_examine_team_id']]['down_score'],
                $value['item_score'],2);
        }

        $same_result_list = M("TeamExamineRelationSame")
            ->where(['team_examine_id'=>$team_examine_id,'comprehensive_status'=>1])
            ->field("be_examine_team_id,comprehensive_status,item_result,item_score")
            ->select();
        foreach($same_result_list as $key=>$value){
            $item_result = json_decode($value['item_result'],true);
            if(!$team_examine_result[$value['be_examine_team_id']]['same_item_result']){
                $team_examine_result[$value['be_examine_team_id']]['same_item_result'] = $item_result;
            }else{
                for($i=0;$i<count($item_result);$i++){
                    $team_examine_result[$value['be_examine_team_id']]['same_item_result'][$i] = bcadd(
                        $team_examine_result[$value['be_examine_team_id']]['same_item_result'][$i],
                        $item_result[$i],2);
                }
            }
            $team_examine_result[$value['be_examine_team_id']]['same_examine_user_count']++;
            $team_examine_result[$value['be_examine_team_id']]['same_score'] = bcadd(
                $team_examine_result[$value['be_examine_team_id']]['same_score'],
                $value['item_score'],2);
        }

        $up_result_list = M("TeamExamineRelationUp")
            ->where(['team_examine_id'=>$team_examine_id,'comprehensive_status'=>1])
            ->field("be_examine_team_id,comprehensive_status,item_result,item_score")
            ->select();
        foreach($up_result_list as $key=>$value){
            $item_result = json_decode($value['item_result'],true);
            if(!$team_examine_result[$value['be_examine_team_id']]['up_item_result']){
                $team_examine_result[$value['be_examine_team_id']]['up_item_result'] = $item_result;
            }else{
                for($i=0;$i<count($item_result);$i++){
                    $team_examine_result[$value['be_examine_team_id']]['up_item_result'][$i] = bcadd(
                        $team_examine_result[$value['be_examine_team_id']]['up_item_result'][$i],
                        $item_result[$i],2);
                }
            }
            $team_examine_result[$value['be_examine_team_id']]['up_examine_user_count']++;
            $team_examine_result[$value['be_examine_team_id']]['up_score'] = bcadd(
                $team_examine_result[$value['be_examine_team_id']]['up_score'],
                $value['item_score'],2);
        }

        $team_examine_result = array_values($team_examine_result);
        $avg_score_array = array();
        foreach($team_examine_result as $key=>$value){
            //计算员工考评平均值
            for($i=0;$i<count($value['down_item_result']);$i++){
                $team_examine_result[$key]['down_item_result'][$i] = bcdiv($value['down_item_result'][$i],$value['down_examine_user_count'],2);
            }
            if($value['down_examine_user_count'] != 0){
                $team_examine_result[$key]['down_score'] = bcdiv($value['down_score'],$value['down_examine_user_count'],2);
            }
            //计算中层考评平均值
            for($i=0;$i<count($value['same_item_result']);$i++){
                $team_examine_result[$key]['same_item_result'][$i] = bcdiv($value['same_item_result'][$i],$value['same_examine_user_count'],2);
            }
            if($value['same_examine_user_count'] != 0) {
                $team_examine_result[$key]['same_score'] = bcdiv($value['same_score'], $value['same_examine_user_count'], 2);
            }
            //计算高层考评平均值
            for($i=0;$i<count($value['up_item_result']);$i++){
                $team_examine_result[$key]['up_item_result'][$i] = bcdiv($value['up_item_result'][$i],$value['up_examine_user_count'],2);
            }
            if($value['up_examine_user_count'] != 0) {
                $team_examine_result[$key]['up_score'] = bcdiv($value['up_score'], $value['up_examine_user_count'], 2);
            }
            //计算三层考评平均值
            $down_item_result = $team_examine_result[$key]['down_item_result'];
            $same_item_result = $team_examine_result[$key]['same_item_result'];
            $up_item_result = $team_examine_result[$key]['up_item_result'];

            //$down_weight = $value['down_weight'];
            $avg_item_result = array();
            for($i=0;$i<count($same_item_result);$i++){
                $down_item_result[$i] = bcmul($down_item_result[$i],$value['down_weight'],2);
                $same_item_result[$i] = bcmul($same_item_result[$i],$value['same_weight'],2);
                $up_item_result[$i] = bcmul($up_item_result[$i],$value['up_weight'],2);

                $avg_item_score = 0;
                if($down_item_result[$i] > 0){
                    $avg_item_score = bcadd($avg_item_score,$down_item_result[$i],2);
                }
                if($same_item_result[$i] > 0){
                    $avg_item_score = bcadd($avg_item_score,$same_item_result[$i],2);
                }
                if($up_item_result[$i] > 0){
                    $avg_item_score = bcadd($avg_item_score,$up_item_result[$i],2);
                }
                $avg_item_result[] = $avg_item_score;
            }
            $team_examine_result[$key]['avg_item_result'] = $avg_item_result;

            $weight_down_score = bcmul($team_examine_result[$key]['down_score'],$value['down_weight'],2);
            $weight_same_score = bcmul($team_examine_result[$key]['same_score'],$value['same_weight'],2);
            $weight_up_score = bcmul($team_examine_result[$key]['up_score'],$value['up_weight'],2);
            $team_examine_result[$key]['avg_score'] = bcadd(bcadd($weight_down_score,$weight_same_score,2),$weight_up_score,2);
            $avg_score_array[] = $team_examine_result[$key]['avg_score'];
        }

        arsort($avg_score_array);
        $avg_score_array = array_flip(array_keys(array_flip(array_values($avg_score_array))));
        foreach($team_examine_result as $key=>$value){
            $team_examine_result[$key]['ranking'] = $avg_score_array[$value['avg_score']] + 1;
        }

        $return_data = array();
        $return_data['item_array'] = json_decode($team_data['item_json'],true);
        $return_data['list_data'] = $team_examine_result;

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 获取选人用人最终结果列表
     */
    public function getEmployingResultList(){
        $team_examine_id = $_REQUEST['team_examine_id']?$_REQUEST['team_examine_id']:$this->errorReturn("缺少班子考评ID");

        $team_data = M("TeamExamine")
            ->where(['team_examine_id'=>$team_examine_id])
            ->field("status,employing_item_json")
            ->find();
        if(!$team_data){
            $this->errorReturn("班子考评ID错误，请重新尝试");
        }
        if($team_data['status'] < 2){
            $this->errorReturn("考核未开始，无法获取最终结果详情");
        }

        $employing_item_array = json_decode($team_data['employing_item_json'],true);

        $team_examine_result = M("TeamExamineResult")
            ->where(['team_examine_id'=>$team_examine_id])
            ->getField("team_id,team_name,team_name_abb");

        if(!$team_examine_result){
            $this->returnJson(503,"无数据");
        }

        foreach($team_examine_result as $key=>$value){
            $team_examine_result[$key]['team_id'] = $key;
            for($i=0;$i<count($employing_item_array);$i++){
                $team_examine_result[$key]['result'][] = [0,0,0,0];
                $team_examine_result[$key]['result_rate'][] = [0,0,0,0];
            }
        }

        $down_result_list = M("TeamExamineRelationDown")
            ->where(['team_examine_id'=>$team_examine_id,'employing_status'=>1])
            ->field("be_examine_team_id,employing_item_result")
            ->select();

        $be_examine_team_id_count = array();
        foreach($down_result_list as $key=>$value){
            $employing_item_result = json_decode($value['employing_item_result'],true);
            if(isset($be_examine_team_id_count[$value['be_examine_team_id']])){
                $be_examine_team_id_count[$value['be_examine_team_id']]++;
            }else{
                $be_examine_team_id_count[$value['be_examine_team_id']] = 1;
            }
            for($i=0;$i<count($employing_item_result);$i++){
                $team_examine_result[$value['be_examine_team_id']]['result'][$i][$employing_item_result[$i]-1]++;
            }
        }

        $team_examine_result = array_values($team_examine_result);
        foreach($team_examine_result as $key=>$value){
            for($i=0;$i<count($value['result_rate']);$i++){
                $team_examine_result[$key]['result_rate'][$i][0] = floatval(bcmul(bcdiv($value['result'][$i][0],$be_examine_team_id_count[$value['team_id']],4),100,2))."%";
                $team_examine_result[$key]['result_rate'][$i][1] = floatval(bcmul(bcdiv($value['result'][$i][1],$be_examine_team_id_count[$value['team_id']],4),100,2))."%";
                $team_examine_result[$key]['result_rate'][$i][2] = floatval(bcmul(bcdiv($value['result'][$i][2],$be_examine_team_id_count[$value['team_id']],4),100,2))."%";
                $team_examine_result[$key]['result_rate'][$i][3] = floatval(bcmul(bcdiv($value['result'][$i][3],$be_examine_team_id_count[$value['team_id']],4),100,2))."%";
            }
        }

        $return_data = array();
        $return_data['item_array'] = json_decode($team_data['employing_item_json'],true);
        $return_data['list_data'] = $team_examine_result;

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 获取新提拔人员考评最终结果列表
     */
    public function getNewPResultList(){
        $team_examine_id = $_REQUEST['team_examine_id']?$_REQUEST['team_examine_id']:$this->errorReturn("缺少班子考评ID");

        $new_p_list = M("TeamExamineNewPromotion")
            ->where(['team_examine_id'=>$team_examine_id])
            ->order("team_id")
            ->getField("new_p_num,team_id,name,date_birth,former_duties,now_duties,appointment_time");

        foreach($new_p_list as $key=>$value){
            $new_p_list[$key]["examine_count"] = 0;
            $new_p_list[$key]["result"] = [0,0,0,0];
            $new_p_list[$key]["result_rate"] = [0,0,0,0];
        }

        $down_result_list = M("TeamExamineRelationDown")
            ->where(['team_examine_id'=>$team_examine_id,'new_p_status'=>1])
            ->field("be_examine_team_id,new_p_result")
            ->select();
        foreach($down_result_list as $key=>$value){
            $new_p_result = json_decode($value['new_p_result'],true);
            foreach($new_p_result as $key1=>$value1){
                $new_p_list[$key1]["examine_count"]++;
                $new_p_list[$key1]["result"][$value1 - 1]++;
            }
        }

        $new_p_list = array_values($new_p_list);

        $team_id_array = array_column($new_p_list,"team_id");
        if(!$team_id_array){
            $this->returnJson(503,"无数据");
        }
        $team_name_array = M("Team")
            ->where(['team_id'=>['in',$team_id_array]])
            ->getField("team_id,name");
        if(!$team_name_array){
            $team_name_array = array();
        }

        foreach($new_p_list as $key=>$value){
            $new_p_list[$key]['date_birth'] = date("Y-m",$value['date_birth']);
            $new_p_list[$key]['appointment_time'] = changeDate($value['appointment_time']);

            $new_p_list[$key]['team_name'] = $team_name_array[$value['team_id']];

            for($i=0;$i<count($value['result']);$i++){
                $new_p_list[$key]['result_rate'][0] = bcmul(bcdiv($value['result'][0],$value['examine_count'],4),100,2)."%";
                $new_p_list[$key]['result_rate'][1] = bcmul(bcdiv($value['result'][1],$value['examine_count'],4),100,2)."%";
                $new_p_list[$key]['result_rate'][2] = bcmul(bcdiv($value['result'][2],$value['examine_count'],4),100,2)."%";
                $new_p_list[$key]['result_rate'][3] = bcmul(bcdiv($value['result'][3],$value['examine_count'],4),100,2)."%";
            }
        }

        $return_data = array();
        $return_data['list_data'] = $new_p_list;

        $this->successReturn("获取成功",$return_data);
    }
}